import express from "express";
import { db } from "../db/index.js";
import { validate, validators } from "../validate.js";
import { makePassword, checkPassword } from "../utils.js";
import { auth } from "../auth.js";

// 定义用户路由
const router = express.Router();

router.post(
  "/register",
  validate(
    validators.username,
    validators.password,
    validators.confirmPassword,
    validators.nickname
  ),
  async (req, res) => {
    const { username, password, nickname } = req.body;
    // 判断用户名是否存在
    const exists =
      await db.findOne`select * from user where username = ${username}`;
    if (exists) {
      return res.json({ success: false, message: "用户名已存在" });
    }
    // 保存用户信息
    const user =
      await db.insert`insert into user (username, password, nickname) values (${username}, ${makePassword(
        password
      )}, ${nickname})`;
    res.json({ success: true, message: "注册成功", object: user });
  }
);

router
  .post(
    "/login",
    validate(validators.username, validators.password),
    async (req, res) => {
      const { username, password } = req.body;
      // 查询用户
      const user =
        await db.findOne`select * from user where username = ${username}`;
      if (user && checkPassword(password, user.password)) {
        // 保存用户 id 到 session
        req.session.userId = user.id;
        return res.json({ success: true, message: "登录成功", object: user });
      }
      res.json({ success: false, message: "用户名或密码错误" });
    }
  )
  // 登出
  .get("/logout", (req, res) => {
    req.session.destroy();
    res.json({ success: true, message: "登出成功" });
  });

router.use(auth);
// 获取登录用户信息
router
  .get("/user/info", async (req, res) => {
    const userId = req.session.userId;
    const user = await db.findOne`select * from user where id = ${userId}`;
    res.json({ success: true, object: user });
  })
  // 修改登录用户密码
  .put(
    "/user/change-password",
    validate(
      validators.oldPassword,
      validators.password,
      validators.confirmPassword
    ),
    async (req, res) => {
      const { oldPassword, password } = req.body;
      const user =
        await db.findOne`select * from user where id = ${req.session.userId}`;
      if (!checkPassword(oldPassword, user.password)) {
        return res.json({ success: false, message: "原密码错误" });
      }
      await db.update`update user set password = ${makePassword(
        password
      )} where id = ${req.session.userId}`;
      res.json({ success: true, message: "密码修改成功" });
    }
  );

export default router;
